<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 7/23/17
 * Time: 1:38 PM
 */
declare(strict_types=1);


namespace wshore\swoole;

use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server as WebSocketServer;
use wshore\swoole\interfaces\WebsocketHandlerInterface;

/**
 * Class SwooleWorker
 * @package wshore\swoole
 */
class SwooleWorker
{
    private $debug = false;

    public function __construct(bool $debug = false)
    {
        $this->debug = $debug;
    }

    /**
     * 获取websocket服务器
     * @param int $port 监听端口
     * @param WebsocketHandlerInterface $handler
     * @return void
     */
    public function startWebsocket(int $port, WebsocketHandlerInterface $handler)
    {
        $server = new WebSocketServer('0.0.0.0', $port);
        $server->on('open', function (WebSocketServer $server, Request $request) use ($handler) {
            if ($this->debug) {
                $info = $server->getClientInfo($request->fd);
                dump($info);
            }
            $handler->onOpen($server, $request);
        });

        $server->on('message', function (WebSocketServer $server, Frame $frame) use ($handler) {
            $handler->onMessage($server, $frame);
        });

        $server->on('close', function (WebSocketServer $server, int $fd) use ($handler) {
            $handler->onClose($server, $fd);
        });
        $server->start();
    }

}